const API_BASE_URL = 'http://api.jbdu.com'
const API_BASE_URL2 = 'http://localhost'

export default function request(api, method, data) {
	let header = {
		'Content-Type': 'application/json'
	}
	uni.showLoading({
		mask: true,
		title: '加载中'
	});

	if (uni.getStorageSync('ACCESS_TOKEN')) header['Access_Token'] = uni.getStorageSync('ACCESS_TOKEN')

	return new Promise((reslove, reject) => {
		uni.request({
			url: (process.env.NODE_ENV === "development" ? API_BASE_URL2 : API_BASE_URL) + api,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: res => {
				let data = res.data
				if (data.statusCode === -1) {
					uni.hideLoading()
					uni.showModal({
						title: "提示",
						content: "登陆过期",
						showCancel: false,
						success: config => {
							if (config.confirm) {
								uni.navigateTo({
									url: '/pages/login/login'
								})
							}
						}
					})
				} else if (data.statusCode === 200 || data.statusCode === 1) {
					reslove(data, res)
					uni.hideLoading()
				} else {
					reject(data.msg || '未知错误')
					uni.hideLoading()
				}
			},
			fail: err => {
				reject(err)
				uni.hideLoading()
			}
		})
	})
}

['OPTIONS', 'GET', 'POST', 'PUT', 'HEAD', 'DELETE', 'TRACE', 'CONNECT'].forEach((method) => {
	request[method] = (api, data) => request(api, method, data)
})
